package com.wedo.book.controller;

import com.netflix.ribbon.proxy.annotation.Http;
import com.wedo.book.pojo.Author;
import com.wedo.book.service.AuthorService;
import com.wedo.common.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("author")
public class AuthorController {

    @Autowired
    private AuthorService authorService;

    /**
     * 根据作者id查找作者
     * @param aid
     * @return
     */
    @GetMapping
    public ResponseEntity<Author> queryAuthorByAid(@RequestParam("aId")Long aid) {
        Author result = this.authorService.queryAuthorByAid(aid);
        if (result == null) {
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 添加作者
     * @param author
     * @return
     */
    @PostMapping
    public ResponseEntity<Author> saveAuthor(@RequestBody Author author) {
        this.authorService.saveAuthor(author);
        return ResponseEntity.ok(author);
    }

    /**
     * 修改作者
     * @param author
     * @return
     */
    @PutMapping
    public ResponseEntity<Author> updateAuthor(@RequestBody Author author){
        if (author.getId() == null) {
            return ResponseEntity.badRequest().build();
        }
        this.authorService.updateAuthor(author);
        return ResponseEntity.ok(author);
    }

    /**
     * 删除作者
     * @param author
     * @return
     */
    @DeleteMapping
    public ResponseEntity<Author> deleteAuthor(@RequestBody Author author) {
        if (author.getId() == null) {
            return ResponseEntity.badRequest().build();
        }
        this.authorService.deleteAuthorById(author.getId());
        return ResponseEntity.ok(author);
    }

    @GetMapping("page")
    public ResponseEntity<PageResult<Author>> queryAuthorByPage(
            @RequestParam(value = "name",required = false)String name,
            @RequestParam(value = "page",defaultValue = "1")Integer page,
            @RequestParam(value = "rows",defaultValue = "6")Integer rows
    ) {
        PageResult<Author> result = this.authorService.queryAuthorByPage(name,page,rows);
        if (result == null || CollectionUtils.isEmpty(result.getItems())) {
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        }
        return ResponseEntity.ok(result);
    }

}
